import json
from qiniu import Auth, BucketManager, put_data
from django.conf import settings
from PIL import Image
import time
import uuid

class ImageHandler:
    def __init__(self):
        self.auth = Auth(settings.QINIU_AK, settings.QINIU_SK)
        self.bucket = settings.BUCKET_NAME
        self.bucket_manager = BucketManager(self.auth)
        self.domain = settings.QINIU_DOMAIN  # 公有空间域名（需在settings.py中配置）

    def generate_upload_token(self, key_prefix=''):
        """生成上传Token（公有空间上传仍需Token授权）"""
        policy = {
            'scope': f"{self.bucket}:{key_prefix}",
            'returnBody': json.dumps({
                'key': '$(key)',
                'hash': '$(etag)'
            })
        }
        return self.auth.upload_token(self.bucket, None, 3600, policy)

    def get_public_url(self, key):
        """生成公有文件的直接访问URL（无需Token）"""
        return f"http://{self.domain}/{key}"

    def delete_file(self, key):
        """删除文件（仍需Token授权）"""
        return self.bucket_manager.delete(self.bucket, key)

    def upload_avatar(self, file_obj, user_uid):
        """上传头像到七牛云公有空间
        Args:
            file_obj: 文件对象
            user_uid: 用户唯一ID
        """
        try:
            img = Image.open(file_obj)
            img.verify()
            file_obj.seek(0)
        except Exception as e:
            raise ValueError("无效的图片文件")

        # 生成唯一文件名
        ext = file_obj.name.split('.')[-1].lower()
        if ext not in ['jpg', 'jpeg', 'png', 'gif','webp']:
            ext = 'jpg'
        key = f"avatars/{user_uid}_{int(time.time())}.{ext}"

        # 上传文件
        token = self.generate_upload_token()
        ret, info = put_data(token, key, file_obj.read())
        if info.status_code != 200:
            raise Exception(f"七牛云上传失败: {info.text_body}")
        
        # Return just the key, not full URL
        return key  # Changed from return self.get_public_url(key)
    
    def upload_product_image(self,file_obj,product):
        try:
            img=Image.open(file_obj)
            img.verify()
            file_obj.seek(0)
        except Exception as e:
            raise ValueError("无效的图片文件")

        # 生成唯一文件名
        ext = file_obj.name.split('.')[-1].lower()
        if ext not in ['jpg', 'jpeg', 'png', 'gif']:
            ext = 'jpg'
        random_str = uuid.uuid4().hex[:8]
        base_key = f"products/{product.product_code}/{product.product_code}_{random_str}.{ext}"
        
        # 上传原图
        token = self.generate_upload_token()
        ret, info = put_data(token, base_key, file_obj.read())
        if info.status_code != 200:
            raise Exception(f"七牛云上传失败: {info.text_body}")
        
        return {
            'key': base_key,
            'ext':ext,
            'size': file_obj.size
        }